from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from cart.utils import merge_cookie_to_reids
from goods.models import SKU
from goods.serializers import UserBrowerHistorySerializer, SKUSerializer
from users.models import User
from users.serializers import RegisterCreateSerializer, UserInfoDetailViewSerializer, SendMailViewSerialize, \
    UserAddrSerializer, AddressTitleSerializer


class UserAuthorizationView(ObtainJSONWebToken):
    """
    用户登陆方法
    """

    def post(self, request, **kwargs):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            response = merge_cookie_to_reids(request, response, user)

        return response


class UserBrowerHistoryView(CreateAPIView):
    """
    保存用户浏览记录
     url:/users/browerhistories/

     1.获取商品id
     2.将商品的id保存在redis中
    """
    serializer_class = UserBrowerHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取用户id
        user_id = request.user.id
        # 建立redis连接
        redis_conn = get_redis_connection('history')
        # 从redis中获取数据
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)
        # 将redis中数据,放在列表中
        skus = []
        for sku_id in sku_ids:
            try:
                sku = SKU.objects.get(pk=sku_id)
            except SKU.DoesNotExist:
                return Response({"message": '获取商品失败'}, 400)
            skus.append(sku)

        # 结果序列化
        sku_serializer = SKUSerializer(skus, many=True)
        return Response(sku_serializer.data, 200)


class UserAddrView(ModelViewSet):
    serializer_class = UserAddrSerializer
    pagination_class = None
    permission_classes = [IsAuthenticated]

    # 获取没有删除的所有的地址
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """重写create方法"""
        if self.request.user.addresses.count() >= 20:
            return Response({"message": "收货地址数量达到上限"}, status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """

        # 获取所有地址
        addrs = self.get_queryset()
        # 创建序列化器,进行序列化
        addrs_serializer = self.get_serializer(addrs, many=True)
        # 获取user
        user = request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': addrs_serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        # 获取先需要删除的地址
        addr = self.get_object()
        # 修改属性
        addr.is_deleted = True
        addr.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        # 获取修改的模型类
        addr = self.get_object()
        serializer = AddressTitleSerializer(addr, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


class VerificationMailView(APIView):
    """激活用户"""

    def get(self, requet):
        # 获取参数 token
        token = requet.query_params.get('token')
        # 校验参数
        if not token:
            return Response({"message": "token失效"}, status.HTTP_400_BAD_REQUEST)
        # 将token 解码  直接返回用户对象
        user = User.get_user_by_token(token)

        # 判断用户是否存在
        if not user:
            return Response({"message": "获取用户失败"}, status.HTTP_400_BAD_REQUEST)

        # 存在修改用户的邮箱激活属性
        user.email_active = True
        user.save()
        return Response({"message": "ok"})


class SendMailView(UpdateAPIView):
    """发送激活邮件"""
    # 设置权限
    permission_classes = [IsAuthenticated]

    # 设置序列化器
    serializer_class = SendMailViewSerialize

    # 设置user对象
    def get_object(self):
        return self.request.user


class UserInfoDetailView(RetrieveAPIView):
    """
    用户中心 显示
    """
    serializer_class = UserInfoDetailViewSerializer

    # 设置权限
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class RegisterCreateView(CreateAPIView):
    serializer_class = RegisterCreateSerializer


class RegisterUsermobileView(APIView):
    """
    校验用户手机号码是否注册

    url:
     GET /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """

    def get(self, request, mobile):
        # 根据手机号码，返回用户数量
        count = User.objects.filter(mobile=mobile).count()
        # 封装数据
        context = {
            'count': count
        }
        # 返回响应
        return Response(context)


class RegisterUsernameView(APIView):
    """
    校验用户名是否存在

    url:
    GET:  /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self, request, username):
        # 通过用户给的用户名，返回用户的个数
        count = User.objects.filter(username=username).count()
        # 封装数据
        context = {
            'count': count
        }
        # 返回响应
        return Response(context)
